package org.example;

import java.util.ArrayList;
import java.util.List;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {

    void inOrder(TreeNode root, List<TreeNode> nodes) {
        if (root == null) {
            return;
        }
        inOrder(root.left, nodes);
        nodes.add(root);
        inOrder(root.right, nodes);
    }

    TreeNode buildTree(List<TreeNode> nodes, int l, int h) {
        if (l > h) {
            return null;
        }
        int mid = (l + h) / 2;
        TreeNode root = nodes.get(mid);
        root.left = buildTree(nodes, l, mid - 1);
        root.right = buildTree(nodes, mid + 1, h);
        return root;
    }

    public TreeNode balanceBST(TreeNode root) {
        List<TreeNode> nodes = new ArrayList<>();
        inOrder(root, nodes);
        return buildTree(nodes, 0, nodes.size() - 1);
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}